import {getServerCookies,getClientCookies} from '~/utils/cookie'
var nodeUrl = require('url')

const needAuthUrls = {
  '/talk' : true ,
}

const loginURL = '/'
const redirectURL = '/chat' ;


export default function({route, req, resp, redirect }) {
  let isClient = process.client ;
  let isServer = process.server ;
  var token , path = loginURL;
  let localRedirectURL = '/' ;
  var url ; 

  if(isServer) {
    let cookies = getServerCookies(req) ;
    path = req.originalUrl;
    token = cookies.token ? cookies.token : '';
    url = nodeUrl.parse(req.url); 
  }

  if(isClient) {
    token = getClientCookies('token');
    path = route.path;
    url = nodeUrl.parse(route.url);
  }

  if(!token) {
    if (url.pathname == loginURL) {
      return ;
    }
    if(path) {
      localRedirectURL = loginURL + '?ref=' + encodeURIComponent(path) ;
    }
    redirect(localRedirectURL) ;
  } else {
    if(url.pathname == loginURL) {
      redirect(localRedirectURL)
    }
  }
}

